package com.dz.syndata.util;

import com.github.pagehelper.util.StringUtil;

import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;



public class HttpRequest {
    final static Logger logger = LoggerFactory.getLogger(HttpRequest.class);

    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url
     *            发送请求的URL
     * @param param
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param,String token)  {
        String result="";
        logger.error("url"+url);
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .method("GET", null)
              .addHeader("Authorization", token)
                .build();
        try {
            Response response = client.newCall(request).execute();
            result=response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
            logger.error(e.toString());
        }
        return result;
    }
    public static String sendGet(String url, String param)  {
        String result="";
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .method("GET", null)
                .build();
        try {
            Response response = client.newCall(request).execute();
            result=response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
            logger.error(e.toString());
        }
        return result;
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Charset", "UTF-8");
            conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    /**
     * okHttp
     * @param path
     * @param params
     * @return
     */
    public static String okHttpGet(String path, Map<String, Object> params) {
        String mPath = "";
        Response response;
        String result = "";
        OkHttpClient client = new OkHttpClient().newBuilder()
                .connectTimeout(60, TimeUnit.SECONDS)//设置连接超时时间
                .readTimeout(60, TimeUnit.SECONDS)//设置读取超时时间

                .build();
        if (params == null) {
            mPath = path;
        } else {
            mPath = path + "?" + appendParams(params);
        }
        System.out.println("mPath"+mPath);

        okhttp3.Request request = new Request.Builder()
                .url(mPath)
                .method("GET", null)
                .build();

        try {
            response = client.newCall(request).execute();
            result = response.body().string();
        } catch (IOException e) {
            result = "请求超时";
            e.printStackTrace();
        }
        return result;

    }

    /**
     * Post请求
     * @param path
     * @param parmas
     * @return
     * @author gxx
     */
    public static String okHttpPost(String path, Map<String, Object> parmas) {
        Response response;
        String result = "";
        RequestBody requestBody = appendBody(parmas);
        OkHttpClient client = new OkHttpClient().newBuilder()
                .connectTimeout(10, TimeUnit.SECONDS)//设置连接超时时间
                .readTimeout(20, TimeUnit.SECONDS)//设置读取超时时间
                .build();
        Request request = new Request.Builder()
                .url(path)
                .method("POST", requestBody)
                .build();
        try {
            response = client.newCall(request).execute();
            result = response.body().string();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;

    }

    public static String appendParams(Map<String, Object> params) {
        List<String> keys = new ArrayList<String>(params.keySet());
        Collections.sort(keys);
        String prestr = "";
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value;
            Integer IntegerValue;
            Object type = params.get(key);
            try{
                if (type instanceof String) {
                    value = (String) params.get(key);
                    try {
                        value = URLEncoder.encode(value, "UTF-8");
                        if (i == keys.size() - 1) {//拼接时，不包括最后一个&字符
                            prestr = prestr + key + "=" + value;
                        } else {
                            prestr = prestr + key + "=" + value + "&";
                        }
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }

                } else {
                    IntegerValue = (Integer) params.get(key);
                    if (i == keys.size() - 1) {//拼接时，不包括最后一个&字符
                        prestr = prestr + key + "=" + IntegerValue;
                    } else {
                        prestr = prestr + key + "=" + IntegerValue + "&";
                    }
                }
            }catch(Exception ex){
                logger.error("处理异常，key={}, value={}",  key, params.get(key));
                logger.error("type is string?{}", (type instanceof String));
                logger.error("系统异常：",  ex);
            }
        }
        return prestr;
    }
    private static RequestBody appendBody(Map<String, Object> parmas) {
        //参数请求体

        FormBody.Builder body = new FormBody.Builder();

        if (parmas == null || parmas.isEmpty()) {
            return body.build();
        }
        for (Map.Entry<String, Object> entry : parmas.entrySet()) {
            body.add(entry.getKey(), entry.getValue().toString());
        }

        return body.build();
    }

}

